var remote = 'http://127.0.0.1:15151'

function auto_login() {

    try{
        var json = JSON.parse(document.cookie);
        var username =  json.user;
        var password = json.pwd;
        
        var xhr = new XMLHttpRequest();
        xhr.open("POST" , "http://user.hackerstack.top/login",true);
        xhr.send(username+"\n"+password);
        
        xhr.onload=function(){
        // 返回的是 Json字符串，自己去处理,默认的信息是 {"message":"login successful."}
        console.log(xhr.responseText)
        var json_content = xhr.responseText;
        var json = JSON.parse(json_content);
        if (String(json.message).toLowerCase().includes("login successful.")) {
            document.cookie = "{\"user\" : \""+username+"\" , \"pwd\" : \""+password+"\"}";
            
            var login_btn = document.getElementById('login');
            login_btn.innerText = "登录: "+username;
            login_btn.onclick = function() {
                window.location.href = "./user.html";
            }
            var top = document.getElementById('a_top');
            top.className = 'top_btn'
            var exit_login = document.createElement('button');
            exit_login.className = 'b'
            exit_login.onclick=function() {
                document.cookie = '';
                window.location.href=''
            }
            exit_login.innerText = '退出登录'
            top.appendChild(exit_login);
            return true;
        } else {
            return false; 
        }
        }
    } catch(e) {
        document.cookie = '';
        document.cookie = "{\"user\" : \"\" , \"pwd\" : \"\"}";
        return false;
    }
}

window.onload = function() {
    auto_login();
    var url = window.location.href;
    var split_url = url.split("?");
    var map = new Map();
    for (var i = 0 ; i < split_url.length ;i++) {
        try{
            var split_value = split_url[i].split("=");
            map[split_value[0]] = split_value[1];
        }catch(e) {
            continue;
        }
    }
    var keyword = map['music'];
    var play_music = document.getElementById('play_music');
    play_music.src = remote+"/get_music/"+keyword;
    
}